/*
 * @lc app=leetcode.cn id=704 lang=cpp
 *
 * [704] 二分查找
 */
#include "include.h"
// @lc code=start
class Solution {
public:
    int search(vector<int>& nums, int target) {
        int left = 0;
        int right = nums.size()-1;
        int middle = right / 2;
        while (right>left+1){
            if (nums[middle] < target){
                left = middle+1;
                middle = (left+right)/2;
            }
            else if (nums[middle] > target){
                right = middle-1;
                middle = (left+right)/2;
            }
            else return middle;
        }
        if (nums[left]==target)return left;
        if (nums[right]==target)return right;
        return -1;
    }
};

class Solution {
public:
    int search(vector<int>& nums, int target) {
        int left = 0, right = nums.size() - 1;
        while(left <= right){
            int mid = (right - left) / 2 + left;
            int num = nums[mid];
            if (num == target) {
                return mid;
            } else if (num > target) {
                right = mid - 1;
            } else {
                left = mid + 1;
            }
        }
        return -1;
    }
};

// @lc code=end

